package com.ccc.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ccc.dto.LoginFormDTO;
import com.ccc.dto.Result;
import com.ccc.dto.UserDTO;
import com.ccc.entity.User;
import com.ccc.mapper.UserMapper;
import com.ccc.service.IUserService;
import com.ccc.utils.RedisConstants;
import com.ccc.utils.RegexUtils;
import com.ccc.utils.UserHolder;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.ccc.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendCode(String phone, HttpSession session) {
        //校验手机号
        //失败:直接返回
        if(RegexUtils.isPhoneInvalid(phone)){
            return Result.fail("手机号格式错误!");
        }
        //成功:生成并发送验证码,并保存在redis
        String code = RandomUtil.randomNumbers(6);
        stringRedisTemplate.opsForValue().set(RedisConstants.LOGIN_CODE_KEY
                +phone,code,RedisConstants.LOGIN_CODE_TTL, TimeUnit.MINUTES);
        //session:phone+验证码
        log.debug("验证码发送成功:"+code);
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //获取手机号,验证码
        String phone = loginForm.getPhone();
        String code = stringRedisTemplate.opsForValue()
                .get(RedisConstants.LOGIN_CODE_KEY+phone);
        //效验
        if(code == null){        //如果手机号不存在
            return Result.fail("验证码错误");
        }
        if (!loginForm.getCode().equals(code)) {
            return Result.fail("验证码错误");
        }
        //一致则检查是否存在用户,不存在则新建
        User user = query().eq("phone",phone).one();
        if (user == null) {
            user =new User();
            user.setPhone(phone);
            user.setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomNumbers(8));
            save(user);
        }
        //对象转为DTO对象
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO,new HashMap<>()
                ,CopyOptions.create().setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName,fieldValue)->fieldValue.toString()));
        //设置token在公共存储空间唯一标识用户
        String token = UUID.randomUUID().toString(true);
        stringRedisTemplate.opsForHash()
                .putAll(RedisConstants.LOGIN_USER_KEY+token,userMap);
        //有效期,将在空闲 / 登出后释放
        stringRedisTemplate.expire(
                RedisConstants.LOGIN_USER_KEY+token,
                RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);
        return Result.ok(token);

    }

    @Override
    public Result signCount() {
        //获取用户
        Long userId = UserHolder.getUser().getId();
        //获取时间
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMM");
        String datePrefix = now.format(formatter);
        //拼接
        String key = RedisConstants.USER_SIGN_KEY + userId + ":" + datePrefix;
        int day = now.getDayOfMonth();
        List<Long> list = stringRedisTemplate.opsForValue().bitField(
                key,
                BitFieldSubCommands.create()
                        .get(BitFieldSubCommands.BitFieldType.unsigned(day))
                        .valueAt(0));
        if(list ==  null || list.isEmpty()){
            return Result.ok(0);
        }
        Long num = list.get(0);
        if(num == 0){
            return Result.ok(0);
        }
        int count = 0;
        //遍历获取连续天数
        //若签到了,继续遍历
        while ((num & 1) == 1) {
            count++;
            num >>>= 1;
        }
        return Result.ok(count);

    }

    @Override
    public Result sign() {
        //获取用户
        Long userId = UserHolder.getUser().getId();
        //获取时间
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMM");
        String datePrefix = now.format(formatter);
        //拼接
        String key = RedisConstants.USER_SIGN_KEY + userId + ":" + datePrefix;
        int day = now.getDayOfMonth();
        //设置
        stringRedisTemplate.opsForValue().setBit(key,day - 1,true);
        return Result.ok() ;
    }
}
